﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Management.Automation;
using ICSharpCode.SharpZipLib.Zip;
using System.IO;


namespace PowerShellZip.Commands
{
    public class CmdletBase : PSCmdlet
    {
        protected object TryGetPipelineProperty(PSObject[] pipeline, string propertyName)
        {
            if (pipeline == null)
                throw new ArgumentNullException("pipeline");
            if (pipeline.Length == 0)
                throw new ArgumentOutOfRangeException("pipeline", "pipeline must contain a object");

            PSPropertyInfo propertyInfo = pipeline[0].Properties[propertyName];
            if (propertyInfo == null)
                return null;
            else
                return propertyInfo.Value;
        }

        protected string TryGetPipelinePropertyAsString(PSObject[] pipeline, string propertyName)
        {
            object value = TryGetPipelineProperty(pipeline, propertyName);
            if (value == null)
                return null;

            return value.ToString();
        }

        protected string RemoveTrailingPathSeparator(string path )
        {
            if (path.StartsWith(new string(Path.DirectorySeparatorChar, 1)) || path.StartsWith(new string(Path.AltDirectorySeparatorChar, 1)) )
                return path.Substring(1);

            return path;
        }

        protected string GetAbsolutePath( string relativePath )
        {
            throw new NotImplementedException();
        }

        protected string GetSubPath(string root, string path)
        {
            if( ! Path.IsPathRooted(path) )
                return RemoveTrailingPathSeparator(path);

            string rootPath = Path.GetFullPath(root).ToLowerInvariant();
            string subPath = path.ToLowerInvariant();

            if (subPath.StartsWith(rootPath))
            {
                subPath = path.Substring(rootPath.Length);
                return RemoveTrailingPathSeparator(subPath);
            }

            return null;
            
        }

    }
}
